import { useState, useEffect } from 'react';
import { Button,Input  } from 'antd';
function ClientShow(): JSX.Element {

  const [clientId, setClientId] = useState('');
  const [status, setStatus] = useState('');
  const [response, setResponse] = useState('');
  const [command, setCommand] = useState('');
  useEffect(() => {
    window.electron.ipcRenderer.on('client-status', (_event, message) => {
      setStatus(message);
    });

    window.electron.ipcRenderer.on('server-response', (_event, { clientId, data }) => {
      setResponse(`客户端 ${clientId}: ${data}`);
    });

    return () => {
      window.electron.ipcRenderer.removeAllListeners('client-status');
      window.electron.ipcRenderer.removeAllListeners('server-response');
    };
  }, []);

  const handleConnect = async () => {
    if (clientId) {
      const result = await window.electron.ipcRenderer.invoke('create-client', clientId);
      console.log(result);
    } else {
      setStatus('请输入客户端 ID');
    }
  };

  const handleSendCommand = async () => {
    if (clientId) {
      const result = await window.electron.ipcRenderer.invoke('send-command', clientId, command);
      console.log(result);
    } else {
      setStatus('请输入客户端 ID');
    }
  };

  return (
    <div className='h-md flex items-center justify-center' >
      <div>
        <h1>TCP 客户端</h1>
        <Input 
          type="text"
          value={clientId}
          className='w-200px placeholder-gray '
          onChange={(e) => setClientId(e.target.value)}
          placeholder="输入客户端 ID"
        />
        <Button className="ml-2" type='primary' onClick={handleConnect}>连接到服务器</Button>
        <p>状态: {status}</p>
        <Input 
          type="text"
          className='w-200px  placeholder-gray '
          value={command}
          onChange={(e) => setCommand(e.target.value)}
          placeholder="输入命令"
        />
        <Button className='ml-2' type='primary' onClick={handleSendCommand}>发送命令</Button>
        <p>服务器响应: {response}</p>

      


        
      </div>

    </div>
  );
}

export default ClientShow;